package com.systop.interceptor;

import com.systop.constant.AuthServiceConstant;
import com.systop.domain.to.SucLoginUserTo;
import com.systop.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;

/**
 * @Description: TODO
 * @Author: jsj
 * @Date: 2023/3/12
 */
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<SucLoginUserTo> threadLocal = new ThreadLocal<>();

    @Autowired
    RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //根据用户账号和token判断用户登录状态
        String userCode = "";
        String token = "";
        for (Cookie cookie : request.getCookies()) {
            // System.out.println(cookie.getName()+"=>"+cookie.getValue());
            if ("userCode".equals(cookie.getName())) {
                userCode = cookie.getValue();
                continue;
            }
            if ("token".equals(cookie.getName())){
                token = cookie.getValue();
                continue;
            }
        }
        if (userCode=="" || token=="") {
            return false;
        }

        //从redis中查询相关用户的登录状态
        SucLoginUserTo user = (SucLoginUserTo) redisUtil.get(AuthServiceConstant.LOGINING_VISITOR + userCode);
        threadLocal.set(user);
        return user == null?false:user.getToken().equals(token);
        // return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //清除相关cookie
        for (Cookie cookie : request.getCookies()) {
            // System.out.println(cookie.getName()+"=>"+cookie.getValue());
            if ("userCode".equals(cookie.getName())) {
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
                continue;
            }
            if ("token".equals(cookie.getName())){
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
                continue;
            }
        }
        // HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
